
import { getBoundingClientRect } from "@/focus/path/until"
import { Ref, ref } from "vue";
type TypeEles = {
  currentEle: HTMLElement,
  currentScroll?: number,
}
type TypeBoxRefs = {
  childRef: Ref<HTMLElement>,
  parentRef: Ref<HTMLElement>,
}
type TypeProps = {
  scroll: string,
  offset: number | string,
}
export function useScrollNumber(boxRefs: TypeBoxRefs, props: TypeProps) {
  let fx: { value: "start" | "end" } = { value: "start" };
  const scrollNo = ref(0)
  function changeScroll(eles: TypeEles) {
    if (!eles.currentEle || !boxRefs.childRef.value || !boxRefs.parentRef) return
    if (props.scroll === "x") {
      scrollNo.value = calculateScroll({
        domLen: getBoundingClientRect(eles.currentEle).width,
        parentLen: getBoundingClientRect(boxRefs.parentRef.value).width,
        childLen: getBoundingClientRect(boxRefs.childRef.value).width,
        eleOffsetStart: eles.currentEle.offsetLeft,
        childOffsetStart: boxRefs.childRef.value.offsetLeft,
        currentScroll: eles.currentScroll,
        offset: props.offset,
        fx: fx,
      })
    } else if (props.scroll === "y") {
      scrollNo.value = calculateScroll({
        domLen: getBoundingClientRect(eles.currentEle).height,
        parentLen: getBoundingClientRect(boxRefs.parentRef.value).height,
        childLen: getBoundingClientRect(boxRefs.childRef.value).height,
        eleOffsetStart: eles.currentEle.offsetTop,
        childOffsetStart: boxRefs.childRef.value.offsetTop,
        currentScroll: eles.currentScroll,
        offset: props.offset,
        fx: fx,
      })
    }
  }
  return {
    scrollNo,
    changeScroll,
  }
}
type TypeScroll = {
  domLen: number,
  parentLen: number,
  childLen: number,
  eleOffsetStart: number,
  childOffsetStart: number,
  currentScroll?: number,
  offset: string | number,
  fx: { value: "start" | "end" },
}
function calculateScroll(params: TypeScroll) {
  let scrollno = 0
  if (params.parentLen >= params.childLen) return scrollno
  if (params.currentScroll != null) {
    scrollno = params.currentScroll
  } else if (params.offset === "center") {
    scrollno = -(params.eleOffsetStart + params.domLen * 0.5 - params.parentLen / 2)
  } else if (typeof params.offset === "number") {
    const _startNo = -(params.eleOffsetStart - params.offset)
    const _endNo = -(params.eleOffsetStart - (params.parentLen - params.offset - params.domLen))
    if (params.childOffsetStart <= _startNo) {
      params.fx.value = "start"
    } else if (params.childOffsetStart >= _endNo) {
      params.fx.value = "end"
    }
    params.fx.value === "end" ? scrollno = _endNo : scrollno = _startNo
  }
  if (scrollno > 0) {
    scrollno = 0
  } else if (scrollno < (- params.childLen + params.parentLen)) {
    scrollno = -params.childLen + params.parentLen
  }
  return scrollno
}